package com.hnluchuan.staff.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hnluchuan.staff.dao.NewsDAO;
import com.hnluchuan.staff.model.News;
import com.hnluchuan.staff.dto.NewsDTO;
import com.hnluchuan.core.support.Page;
import com.hnluchuan.utils.common.BeanMapper;

@Service
public class NewsService extends BaseService {
	
	@Autowired
	private NewsDAO newsDAO;
	
	public List<NewsDTO> find(NewsDTO query, Page page) {
		List<News> models = newsDAO.find(query, page);
		List<NewsDTO> dtos = toDTOs(models);
		return dtos;
	}
	
	public List<NewsDTO> findAll() {
		return this.find(new NewsDTO(), null);
	}
	
	public List<NewsDTO> findAll(NewsDTO query) {
		return this.find(query, null);
	}
	
	public List<NewsDTO> find(Page page) {
		return this.find(new NewsDTO(), page);
	}
	
	public List<NewsDTO> find(int count) {
		Page page = new Page();
		page.setPage(1);
		page.setPageSize(count);
		return this.find(new NewsDTO(), page);
	}
	
	public Long create(NewsDTO dto) {
		News model = new News();
		toModel(model, dto);
		return newsDAO.create(model);
	}
	
	public NewsDTO load(Long id) {
	    News model = newsDAO.load(id);
	    return toDTO(model);
    }

	public void updateAllFields(NewsDTO dto) {
		News model = newsDAO.load(dto.getId());
		toModel(model, dto);
		newsDAO.update(model);
    }

	public void deleteByIds(Long[] ids) {
		//throw new RuntimeException("默认禁止删除，请确认是物理删除还是逻辑删除");

		if (ids != null) {
			for (Long id : ids) {
				newsDAO.deleteById(id);
			}
		}
    }
	
	public void deleteById(Long id) {
		this.deleteByIds(new Long[] {id});
	}

	public NewsDTO findOne(NewsDTO query) {
		News model = newsDAO.findOne(query);
		return toDTO(model);
	}
	
	private List<NewsDTO> toDTOs(List<News> models) {
		if (CollectionUtils.isEmpty(models)) {
			return new ArrayList<NewsDTO>(0);
		}
		List<NewsDTO> dtos = new ArrayList<NewsDTO>(models.size());
		for (News model : models) {
	        NewsDTO dto = toDTO(model);
	        dtos.add(dto);
        }
	    return dtos;
    }
    
    private NewsDTO toDTO(News model) {
		if (model == null) {
			return null;
		}
		NewsDTO dto = BeanMapper.map(model, NewsDTO.class);
		
		return dto;
	}
	
	private void toModel(News model, NewsDTO dto) {
		BeanMapper.copy(dto, model);
    }
	
	@SuppressWarnings("unused")
	private List<News> toModels(List<NewsDTO> dtos) {
		if (CollectionUtils.isEmpty(dtos)) {
			return new ArrayList<News>(0);
		}
		List<News> models = new ArrayList<News>(dtos.size());
		for (NewsDTO dto : dtos) {
	        News model = new News();
	        toModel(model, dto);
	        models.add(model);
        }
		return models;
	}
}
